<?php

namespace App\Repository;

use App\Entity\MoneyLogType;
use App\Entity\MoneyStatic;
use App\Entity\MoneyType;
use App\Entity\User;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Common\Persistence\ManagerRegistry;

/**
 * @method MoneyStatic|null find($id, $lockMode = null, $lockVersion = null)
 * @method MoneyStatic|null findOneBy(array $criteria, array $orderBy = null)
 * @method MoneyStatic[]    findAll()
 * @method MoneyStatic[]    findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
 */
class MoneyStaticRepository extends ServiceEntityRepository
{
    public $moneyTypeRepository;
    public $moneyLogTypeRepository;

    public function __construct(
        ManagerRegistry $registry
        ,MoneyTypeRepository $moneyTypeRepository
        ,MoneyLogTypeRepository $moneyLogTypeRepository
    )
    {
        parent::__construct($registry, MoneyStatic::class);
        $this->moneyTypeRepository = $moneyTypeRepository;
        $this->moneyLogTypeRepository = $moneyLogTypeRepository;
    }

    /**
     * @param User $user
     * @param $
     * @param MoneyType $moneyType
     * @param MoneyLogType $logType
     * @return MoneyStatic|null
     * @throws \Doctrine\ORM\ORMException
     * @throws \Doctrine\ORM\OptimisticLockException
     */
    public function getUserMoneyStaticByType(User $user,MoneyType $moneyType,MoneyLogType $logType)
    {
        $money = $this->findOneBy(array("moneyType"=>$moneyType));
        if (!$money) {
            $money = new MoneyStatic();
            $money->setUser($user)
                ->setMoneyType($moneyType)
                ->setLogType($logType)
                ->setMoney(0);
            $this->_em->persist($moneyType);
            $this->_em->flush();
        }
        return $money;
    }
}
